package com.swu.cx.kotlinmodule.proxy

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

class DynamicProxy constructor(): RentHouse, RentCar {

    companion object {
        private const val FIND_HOUSE = "findHouse"
        private const val FIND_CAR = "findCar"
    }

    private var rentHouse: RentHouse? = null

    private var rentCar: RentCar? = null

    constructor(rentHouse: RentHouse): this() {
        this.rentHouse = rentHouse
    }

    constructor(rentCar: RentCar): this() {
        this.rentCar = rentCar
    }

    private val agent = Proxy.newProxyInstance(
        DynamicProxy::class.java.classLoader,
            arrayOf(RentHouse::class.java, RentCar::class.java), object : InvocationHandler {
        override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
            val arr = method.toString().replace("()","").split(".")
            when(arr[arr.size - 1]) {
                FIND_HOUSE -> service { rentHouse?.findHouse() }
                FIND_CAR -> service { rentCar?.findCar() }
            }
            return null
        }

    })

    override fun findHouse() {
        (agent as RentHouse).findHouse()
    }

    override fun findCar() {
        (agent as RentCar).findCar()
    }

    private fun service(block: (() -> Unit)?) {
        block ?: return
        println("开始服务....")
        block.invoke()
        println("给个五星好评奥")
    }
}